package com.daocao.hua.fragment;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.hua.activity.HelpDetailActivity;
import com.daocao.hua.R;
import com.daocao.hua.adapter.MessageAdapterNew;
import com.daocao.hua.api.callback.MessageContract;
import com.daocao.hua.api.requestInfo.MessageRequest;
import com.daocao.hua.constant.Const;
import com.daocao.hua.interfaces.OnRecyclerViewListener;
import com.daocao.hua.model.MessageModel;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.view.CircularProgress;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息界面
 * Created by MasterDong on 16/8/11.
 */
public class MessageFragment extends BaseFragment implements View.OnClickListener, MessageContract.View {


    private List<MessageModel.DataList> list = new ArrayList<MessageModel.DataList>();
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private int lastVisibleItem;
    private int pastDuePageIndex;
    private MessageAdapterNew adapter = null;
//    private CircularProgress loading;
    private TextView nothing;
    private boolean hasData;
    private MessageRequest api;


    @Override
    protected int setLayoutId() {
        return R.layout.fragment_message;
    }

    @Override
    protected void initView() {
        api = MessageRequest.create();
        api.attachView(this);
        nothing = (TextView) root.findViewById(R.id.nothing);
//        loading = (CircularProgress) root.findViewById(R.id.progressBar);
        recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        //刷新
        swipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(R.color.d_refresh_color_red);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(true);
                getMessageInfo(Const.PullType.PULL_DOWN, 1);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView,
                                             int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                try {
                    if (adapter == null) return;
                    if (newState == RecyclerView.SCROLL_STATE_IDLE
                            && lastVisibleItem + 1 == adapter.getItemCount()) {
                        swipeRefreshLayout.setRefreshing(true);
                        getMessageInfo(Const.PullType.PULL_UP, pastDuePageIndex + 1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        getMessageInfo(Const.PullType.PULL_DOWN, 1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        showLoading(true);
        getMessageInfo(Const.PullType.PULL_DEFAULT, 1);
        MobclickAgent.onPageStart("MessageFragment");
    }


    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MessageFragment");
    }

    /**
     * 是否显示加载框
     *
     * @param
     */
//    private void showLoading(boolean b) {
//        if (b) {
//            if (loading != null) loading.setVisibility(View.VISIBLE);
//        } else {
//            if (loading != null) loading.setVisibility(View.GONE);
//        }
//    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {
//        showLoading(false);
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onRequestStart() {
        if (swipeRefreshLayout!=null) {
            swipeRefreshLayout.setRefreshing(true);
        }
    }

    @Override
    public void getMessageInfoSuccess(int type, int pageIndex, MessageModel model) {

        list = model.getData();

        if (list.size() <= 0) {
            if (!hasData)
                nothing.setVisibility(View.VISIBLE);
            else
                ToastUtil.makeText(getActivity(), getResources().getString(R.string.no_more_date_text), Toast.LENGTH_SHORT).show();
            return;
        }
        hasData = true;
        if (adapter == null)
            adapter = new MessageAdapterNew(getActivity(), model.getData());
        if (type == Const.PullType.PULL_UP) {

            if (pageIndex <= model.getPager().getAllPages()) {
                adapter.addList(model.getData());
                ToastUtil.makeText(getActivity(), getResources().getString(R.string.loading_finish_text), Toast.LENGTH_SHORT).show();
            } else {
                ToastUtil.makeText(getActivity(), getResources().getString(R.string.no_more_date_text), Toast.LENGTH_SHORT).show();
            }
        } else {
            adapter = new MessageAdapterNew(getActivity(), model.getData());
            recyclerView.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
        pastDuePageIndex = pageIndex;
        adapter.setOnRecyclerViewListener(new myOnRecyclerViewListener());
        nothing.setVisibility(View.GONE);
    }

    /**
     * 列表点击事件监听
     */
    class myOnRecyclerViewListener implements OnRecyclerViewListener {

        @Override
        public void onItemClick(List<?> list, int position) {
            List<MessageModel.DataList> l = (List<MessageModel.DataList>) list;

            Intent intent = new Intent();
            intent.putExtra("id", l.get(position).getId());
            intent.putExtra("type", Const.FragmentType.MESSAGE);
            intent.setClass(getActivity(), HelpDetailActivity.class);
            startActivity(intent);
            getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
        }

        @Override
        public boolean onItemLongClick(List<?> list, int position) {
            return false;
        }
    }

    /**
     * 获取消息表
     */
    private void getMessageInfo(final int type, final int pageIndex) {
        api.getMessageInfo(type, pageIndex);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        api.detachView();
        api = null;
    }
}
